#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
千问 API key 测试脚本

python3 -m virtualenv .venv
source .venv/bin/activate

pip install requests

export DASHSCOPE_API_KEY='你的千问API_key'
"""

import os
import requests
import json

def test_qwen_api():
    """测试千问 API key 是否可用"""
    
    # 从环境变量获取 API key
    api_key = os.getenv('DASHSCOPE_API_KEY')
    
    if not api_key:
        print("❌ 错误: 请设置环境变量 DASHSCOPE_API_KEY")
        print("   例如: export DASHSCOPE_API_KEY='your_api_key_here'")
        return False
    
    # 千问 API 端点
    url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
    
    # 请求头
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    
    # 最简单的测试请求
    data = {
        "model": "qwen-turbo",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": "你好"
                }
            ]
        },
        "parameters": {
            "max_tokens": 10
        }
    }
    
    try:
        print("🔄 正在测试千问 API...")
        print(f"   使用模型: {data['model']}")
        print(f"   API Key: {api_key[:8]}...{api_key[-4:]}")
        
        response = requests.post(url, headers=headers, json=data, timeout=30)
        
        if response.status_code == 200:
            result = response.json()
            if 'output' in result and 'text' in result['output']:
                print("✅ API key 测试成功!")
                print(f"   响应: {result['output']['text']}")
                return True
            else:
                print("❌ API 响应格式异常")
                print(f"   响应内容: {json.dumps(result, indent=2, ensure_ascii=False)}")
                return False
        else:
            print(f"❌ API 请求失败 (状态码: {response.status_code})")
            try:
                error_info = response.json()
                print(f"   错误信息: {json.dumps(error_info, indent=2, ensure_ascii=False)}")
            except:
                print(f"   错误信息: {response.text}")
            return False
            
    except requests.exceptions.Timeout:
        print("❌ 请求超时")
        return False
    except requests.exceptions.RequestException as e:
        print(f"❌ 网络请求异常: {e}")
        return False
    except Exception as e:
        print(f"❌ 未知错误: {e}")
        return False

if __name__ == "__main__":
    print("=" * 50)
    print("千问 API Key 测试脚本")
    print("=" * 50)
    
    success = test_qwen_api()
    
    print("=" * 50)
    if success:
        print("🎉 测试完成: API key 可正常使用")
    else:
        print("💥 测试失败: API key 无法使用")
        print("\n📝 检查事项:")
        print("   1. 确认 API key 是否正确")
        print("   2. 确认账户是否有余额")
        print("   3. 确认网络连接是否正常")
        print("   4. 确认 API key 是否已激活")
